package com.citrix.gs.util;

import java.io.IOException;
import java.util.List;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.citrix.gs.util.beacon.BeaconCI;
import com.citrix.gs.util.common.CIInfo;
import com.offbytwo.jenkins.model.Job;


public class RunFailed {
    
    private static final Logger logger = LoggerFactory.getLogger(RunFailed.class);
    
    @SuppressWarnings("unused")
    private CIInfo ciInfo;
    private BeaconCI ci;
    
    
    public RunFailed(CIInfo ciInfo) {
        this.ciInfo = ciInfo;
        this.ci = new BeaconCI(ciInfo);
    }
    
    public RunFailed(BeaconCI ci) {
        this.ci = ci;
    }
    
    
    public void run() {
        
        // Get Failed jobs from failed view
        try {
            List<Job> failedJobs = ci.getView("Failed").getJobs(); // TODO: fix the hard coded view name
            
            if(failedJobs != null && failedJobs.size() > 0) {
                
                ci.getTopJobs(failedJobs).stream().forEach(job -> {
                    try {
                        logger.info("Build job: {} on CI: {}", job.getName(), ci.getHostURL());
                        if(job.getClient() == null) { //TODO: workaround for jenkins client is null when get job
                            job.setClient(ci.getClient());
                        }
                        job.build(false);
                    } catch (Exception e) {
                        logger.error("Failed to build job: {}", job.getName(), e);
                    }
                });
            }
            
        } catch (IOException e) {
            e.printStackTrace();
        } 
    }
    
    

}
